<template>
  <type-wrapper :name="name">
    <div class="upload-container">
      <el-image 
        v-if="extra.selectedValue"
        class="preview-image"
        :src="extra.selectedValue" 
        :preview-src-list="[extra.selectedValue]">
      </el-image>
      <el-button style="position:relative">
        <input
          class="upload-input"
          type="file"
          name="file"
          id=""
          @change="onUploadButtonClick"
        />
        上传</el-button>
    </div>
  </type-wrapper>
</template>

<script>
import TypeWrapper from './type-wrapper.vue'
import { Button } from 'element-ui'

export default {
  components: {
    'type-wrapper': TypeWrapper,
    'el-button': Button,
  },
  data() {
    return {
    }
  },
  props: {
    name: {
      type: String,
    },
    config: {
      type: String,
    },
    extra: {
      type: Object,
    }
  },
  methods: {
    onChange(e) {
      this.$emit('change', e)
    },
    onUploadButtonClick(event) {
      this.uploader.handleUpload(event)
    }
  },
  mounted() {
    const {uploadConfig: {host, uploadApi}, uploadModule: { Upload }} = window.$scope

    this.uploader = new Upload(host, uploadApi);
    this.uploader.addEventListener(
      "upload-success",
      (type, filename, resourceUrl) => {
        this.$emit('change', resourceUrl)
      }
    );
  }
}
</script>

<style scoped>
.upload-input{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  cursor: pointer;
}
.preview-image{
  width: 38px;
  height: 38px;
  border-radius: 4px;
  margin-right: 10px;
}
.upload-container{
  display: flex;
  align-items: center;
}
</style>